package com.yuran.ranCloud.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yuran.common.annotation.Anonymous;
import com.yuran.common.config.RuoYiConfig;
import com.yuran.common.utils.SecurityUtils;
import com.yuran.common.utils.StringUtils;
import com.yuran.common.utils.file.FileUploadUtils;
import com.yuran.common.utils.file.FileUtils;
import com.yuran.framework.config.ServerConfig;
import com.yuran.ranCloud.domain.FileTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuran.common.annotation.Log;
import com.yuran.common.core.controller.BaseController;
import com.yuran.common.core.domain.AjaxResult;
import com.yuran.common.enums.BusinessType;
import com.yuran.ranCloud.domain.RanCloudFiles;
import com.yuran.ranCloud.service.IRanCloudFilesService;
import com.yuran.common.utils.poi.ExcelUtil;
import com.yuran.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 云盘文件Controller
 * 
 * @author yuran
 * @date 2023-11-23
 */
@RestController
@RequestMapping("/ranCloud/ranFiles")
public class RanCloudFilesController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(RanCloudFilesController.class);

    @Autowired
    private IRanCloudFilesService ranCloudFilesService;

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    /**
     * 查询云盘文件列表
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:list')")
    @GetMapping("/list")
    public TableDataInfo list(RanCloudFiles ranCloudFiles)
    {
        startPage();
        List<RanCloudFiles> list = ranCloudFilesService.selectRanCloudFilesList(ranCloudFiles);
        return getDataTable(list);
    }

    /**
     *查询真实路径下的文件
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:query')")
    @GetMapping("/files")
    public AjaxResult files(String fileUrl){
        try {
            return AjaxResult.success(ranCloudFilesService.realFilesQuery(fileUrl));
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.toString());
        }
    }

    /**
     * 真实路径创建文件夹
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:add')")
    @PostMapping("/createFile")
    public AjaxResult createFile(String path){
        // 创建文件夹路径
        try {
            boolean result = ranCloudFilesService.realCreateFile(path);
            if (result) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error();
            }
        }catch (Exception e){
            return AjaxResult.error(e.toString());
        }
    }

    /**
     * 真实路径删除文件
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:remove')")
    @Log(title = "删除文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteFile")
    public AjaxResult deleteFile(String path){
        try {
            boolean result = ranCloudFilesService.realDeleteFile(path);
            if (result) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error();
            }
        }catch (Exception e){
            return AjaxResult.error(e.toString());
        }
    }

    /**
     * 导出云盘文件列表
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:export')")
    @Log(title = "云盘文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RanCloudFiles ranCloudFiles)
    {
        List<RanCloudFiles> list = ranCloudFilesService.selectRanCloudFilesList(ranCloudFiles);
        ExcelUtil<RanCloudFiles> util = new ExcelUtil<RanCloudFiles>(RanCloudFiles.class);
        util.exportExcel(response, list, "云盘文件数据");
    }

    /**
     * 获取云盘文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:query')")
    @GetMapping(value = "/{fileId}")
    public AjaxResult getInfo(@PathVariable("fileId") Long fileId)
    {
        return success(ranCloudFilesService.selectRanCloudFilesByFileId(fileId));
    }

    /**
     * 新增云盘文件
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:add')")
    @Log(title = "云盘文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RanCloudFiles ranCloudFiles)
    {
        return toAjax(ranCloudFilesService.insertRanCloudFiles(ranCloudFiles));
    }

    /**
     * 修改云盘文件
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:edit')")
    @Log(title = "云盘文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RanCloudFiles ranCloudFiles)
    {
        return toAjax(ranCloudFilesService.updateRanCloudFiles(ranCloudFiles));
    }

    /**
     * 删除云盘文件
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranFiles:remove')")
    @Log(title = "云盘文件", businessType = BusinessType.DELETE)
	@DeleteMapping("/{fileIds}")
    public AjaxResult remove(@PathVariable Long[] fileIds)
    {
        return toAjax(ranCloudFilesService.deleteRanCloudFilesByFileIds(fileIds));
    }

    /**
     * 通用上传请求（单个）-真实路径上传
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:add')")
    @Log(title = "上传云盘文件", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, String path) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPathRan() + path;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.uploadRan(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:add')")
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPathRan();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files)
            {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @PreAuthorize("@ss.hasPermi('ranCloud:ranHome:download')")
    @Log(title = "下载云盘文件", businessType = BusinessType.UPDATE)
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getCloudFile() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
